from utils import log_info, log_exception, log_error
from typing import List, Optional
from .base_dao import BaseDAO
from models.exam_question_detail import ExamQuestionDetail


class ExamQuestionDetailDAO(BaseDAO[ExamQuestionDetail]):
    """考试题目详情表数据访问对象"""

    def __init__(self):
        """
        初始化ExamQuestionDetailDAO
        """
        super().__init__(ExamQuestionDetail)

    def _get_table_name(self) -> str:
        """获取表名"""
        return "exam_question_details"

    def _get_primary_key(self) -> str:
        """获取主键名"""
        return "id"

    def get_by_exam_id(self, exam_id: int) -> List[ExamQuestionDetail]:
        """
        根据考试ID获取所有题目详情
        :param exam_id: 考试ID
        :return: 考试题目详情实体列表
        """
        sql = "SELECT * FROM exam_question_details WHERE exam_id = ?"
        params = (exam_id,)
        return self._execute_query(sql, params)

    def get_by_exam_and_question(self, exam_id: int, question_id: int) -> Optional[ExamQuestionDetail]:
        """
        根据考试ID和题目ID获取题目详情
        :param exam_id: 考试ID
        :param question_id: 题目ID
        :return: 考试题目详情实体，如果不存在返回None
        """
        sql = "SELECT * FROM exam_question_details WHERE exam_id = ? AND question_id = ?"
        params = (exam_id, question_id)
        return self._execute_query(sql, params, single_result=True)

    def get_incorrect_questions(self, exam_id: int) -> List[ExamQuestionDetail]:
        """
        获取考试中的错题详情
        :param exam_id: 考试ID
        :return: 错题详情实体列表
        """
        sql = "SELECT * FROM exam_question_details WHERE exam_id = ? AND is_correct = 0"
        params = (exam_id,)
        return self._execute_query(sql, params)

    def delete_by_exam_id(self, exam_id: int) -> bool:
        """
        根据考试ID删除所有题目详情
        :param exam_id: 考试ID
        :return: 删除成功返回True，否则返回False
        """
        sql = "DELETE FROM exam_question_details WHERE exam_id = ?"
        params = (exam_id,)
        try:
            conn = self._get_connection()
            if not conn:
                log_error("无法获取数据库连接")
                return False
            cursor = conn.cursor()
            cursor.execute(sql, params)
            conn.commit()
            if cursor.rowcount > 0:
                log_debug(f"删除考试{exam_id}的所有题目详情成功，共删除{cursor.rowcount}条记录")
                return True
            log_debug(f"未找到考试{exam_id}的题目详情，删除失败")
            return False
        except Exception as e:
            log_exception(f"删除考试题目详情失败: {str(e)}")
            return False
        finally:
            if conn:
                self.db_pool.release_connection(conn)

    def bulk_create(self, exam_question_details: List[ExamQuestionDetail]) -> bool:
        """
        批量创建考试题目详情
        :param exam_question_details: 考试题目详情列表
        :return: 创建成功返回True，否则返回False
        """
        if not exam_question_details:
            return True

        try:
            conn = self._get_connection()
            if not conn:
                log_error("无法获取数据库连接")
                return False
            cursor = conn.cursor()

            # 准备批量插入的数据
            fields = ['exam_id', 'question_id', 'question_text', 'option_a', 'option_b', 'option_c', 'option_d', 'correct_answer', 'type', 'image_data']
            placeholders = ', '.join(['?' for _ in fields])
            values = []

            for detail in exam_question_details:
                values.append((
                    detail.exam_id,
                    detail.question_id,
                    detail.question_text,
                    detail.option_a,
                    detail.option_b,
                    detail.option_c,
                    detail.option_d,
                    detail.correct_answer,
                    detail.type,
                    detail.image_data
                ))

            # 执行批量插入
            cursor.executemany(f"INSERT INTO exam_question_details ({', '.join(fields)}) VALUES ({placeholders})", values)
            conn.commit()
            log_debug(f"批量创建考试题目详情成功，共{len(exam_question_details)}条记录")
            return True
        except Exception as e:
            log_exception(f"批量创建考试题目详情失败: {str(e)}")
            return False
        finally:
            if conn:
                self.db_pool.release_connection(conn)